#!/usr/bin/env python
"""
Acorn-SDR (A Collaboration of Radio Nodes)
(c) Bob Cowdery (G3UKB) 2009

File: outstr_service.py
Date: January 2009

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

The author can be reached by email at

bob@g3ukb.co.uk

================================================================================
Module Description:

The streaming out service.

"""

#-------------------------------------------------------------------------------
# System imports
import sys
import os
import traceback
from time import sleep
from Numeric import *
import Ice, IceStorm

# Application imports
import outstr
import ice_helpers
import utils

# Import the Ice interface definitions
import AcornLifeCycle
import AcornRxUpdate
import AcornRxOut
import AcornPersist

#===============================================================================
# Ice life-cycle events for the GUI
class LifeCycleI(AcornLifeCycle.LifeCycle):
    
    #---------------------------------------------------------------------------   
    def __init__(self, service, outstr_impl):
        self.outstr_impl = outstr_impl
        self.service = service
      
    #---------------------------------------------------------------------------
    def start(self, current=None):
        self.outstr_impl.stream_on()
     
    #---------------------------------------------------------------------------   
    def stop(self, current=None):
        self.outstr_impl.stream_off()
    
    #---------------------------------------------------------------------------    
    def terminate(self, current=None):
        self.service.terminate()

#===============================================================================
# Ice receiver for the audio stream
class RxOutI(AcornRxOut.RxOut):
    
    #---------------------------------------------------------------------------
    def __init__(self, outstr_impl):
      self.outstr_impl = outstr_impl
    
    #---------------------------------------------------------------------------   
    def data(self, samples, current=None):
        
        # Output the output stream
        self.outstr_impl.output(samples)
        self.outstr_impl.apply_updates()

#===============================================================================
# Ice config events for streaming out
class RxConfigI(AcornRxUpdate.RxConfig):
    
    #---------------------------------------------------------------------------   
    def __init__(self, outstr_impl, persist, config_map):
        self.outstr_impl = outstr_impl
        self.persist = persist
        self.map = config_map
      
    #---------------------------------------------------------------------------   
    def configUpdate(self, name, current=None):
        # Update the OutStr configuration
        if name in self.map:
            # Its something we are interested in so go get it
            item = utils.persist_get(self.persist, 'Profile', name)
            # and pass it in
            self.map[name](item)
            
#===============================================================================
# The main application class for audio streaming in:
#   Subscribes to stream-events
#   Reads audio blocks via Jack and sends to dsp       
#===============================================================================
class OutstrService(Ice.Application):
        
    #---------------------------------------------------------------------------
    def __init__(self):
        self.close = False
    
    #---------------------------------------------------------------------------
    # Run the app
    def run(self, args):
       
        #-----------------------------------------------------------------------
        # persist interface
        persist = ice_helpers.get_interface('Outstr Service', self.communicator, AcornPersist.PersistPrx, 'Persist.Proxy')     
        # Get config
        ch1 = utils.persist_get(persist, 'Profile', 'jack.outdevch1')
        ch2 = utils.persist_get(persist, 'Profile', 'jack.outdevch2')
        frames = utils.persist_get(persist, 'Profile', 'audio.frames')
        rate = utils.persist_get(persist, 'Profile', 'audio.rate')
        fixed = utils.persist_get(persist, 'Profile', 'audio.outputfixed')
        
        #-----------------------------------------------------------------------
        # Initialise the stream out
        outstr_impl = outstr.AudioOut(ch1, ch2, rate, frames, fixed)
        config_map = {'audio.frames': outstr_impl.set_audioframes, 'audio.rate': outstr_impl.set_audiorate}
        
        #-----------------------------------------------------------------------
        # Event names used here
        subscribe_to_lc = 'life_cycle_events'
        subscribe_to_rx_config = 'rx_config_events'
  
        #-----------------------------------------------------------------------
        # This is the same for both publishers and subscribers
        # Get the IceStorm topic manager interface
        manager = ice_helpers.get_topic_manager('Outstr Service', self.communicator)
    
        # Retrieve the subscriber topic
        life_cycle_topic = ice_helpers.get_topic('Outstr Service', manager, subscribe_to_lc)
        rx_config_topic = ice_helpers.get_topic('Outstr Service', manager, subscribe_to_rx_config)
        
        #-----------------------------------------------------------------------
        # Subscriber side
        # Create an adapter for the subscriber   
        adapter_1 = self.communicator().createObjectAdapter("LifeCycle.Subscriber")
        subId_1 = Ice.Identity()
        subId_1.name = Ice.generateUUID()
        # Add the stream command interface
        subscriber_1 = adapter_1.add(LifeCycleI(self, outstr_impl), subId_1)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('Outstr Service', life_cycle_topic, subscriber_1, id)
        # Now we can receive callbacks   
        adapter_1.activate()
        
        adapter_2 = self.communicator().createObjectAdapter("RxConfig.Subscriber")
        subId_2 = Ice.Identity()
        subId_2.name = Ice.generateUUID()        
        # Add the update interface
        subscriber_2 = adapter_2.add(RxConfigI(outstr_impl, persist, config_map), subId_2)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('Outstr Service', rx_config_topic, subscriber_2, id)
        # Now we can receive callbacks   
        adapter_2.activate()
        
        #-----------------------------------------------------------------------
        # One way audio channel in (streamout refers to the receiver)
        audio_adapter = self.communicator().createObjectAdapter("RxOut")
        audio_adapter.add(RxOutI(outstr_impl), self.communicator().stringToIdentity("rxout"))        
        # Now we can receive callbacks for audio 
        audio_adapter.activate()
        
        print 'Acorn-SDR (Outstr Service) running..'
        
        #-----------------------------------------------------------------------
        # Wait for closedown
        while not self.close:
            # Idle loop for doing any other work
            sleep(1)

        # Unsubscribe all subscribed objects.
        # Causes issues at the moment
        #life_cycle_topic.unsubscribe(subscriber_1)
        #rx_config_topic.unsubscribe(subscriber_2)

    #---------------------------------------------------------------------------
    # Terminate
    def terminate(self):
        self.close = True
        
#===============================================================================
#===============================================================================
# Start from the command line
if __name__ == "__main__":
   
    app = OutstrService()
    app.main(sys.argv, sys.argv[1])
  
    # Announce we are going 
    print 'Acorn-SDR (Outstr Service) closing..'